package com.sphd.Restaurant.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.sphd.Restaurant.R;
import com.sphd.Restaurant.adapters.AffirmAdapter;
import com.sphd.Restaurant.base.BaseActivity;
import com.sphd.Restaurant.infos.AddressInfo;
import com.sphd.Restaurant.infos.CouponInfo;
import com.sphd.Restaurant.infos.Dishes;
import com.sphd.Restaurant.infos.RestaurantInfo;
import com.sphd.Restaurant.infos.VipInfo;
import com.sphd.Restaurant.model.Model;
import com.sphd.Restaurant.presenter.AffirmOrderP;
import com.sphd.Restaurant.utils.AppManager;
import com.sphd.Restaurant.utils.Constants;
import com.sphd.Restaurant.views.AffirmOrderView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.pedant.SweetAlert.SweetAlertDialog;

public class AffirmOrderActivity extends BaseActivity implements AffirmOrderView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.my_recyclerView)
    RecyclerView myRecyclerView;
    @BindView(R.id.tv_affirm_allmoney)
    TextView tvAffirmAllmoney;
    @BindView(R.id.bt_order_ok)
    Button btOrderOk;
    Intent intent;
    Bundle bundle;
    AffirmOrderP affirmOrderP;
    RestaurantInfo restaurantInfo;
    List<Dishes> dishes;
    AffirmAdapter affirmAdapter;
    List<VipInfo> vipInfos;
    int type;
    View headerView;
    private LinearLayout llSelectAddress, lladdress, llselectCoupons;//地址布局
    TextView payF, addAddress, affirName, affirPhone, affirAddress;
    int men_geage;//详细判断此会员的身份 0：普通会员 1：折扣会员 2：充值会员 （表示账户有钱）
    int chooseTapye;
    double cglowlimit;
    double goToMoney;
    double allMoneyoney;
    double lastprice;//订单中现金支付的金额
    String isVip;
    double account;
    List<AddressInfo> addressInfoList;
    List<CouponInfo> couponInfos;
    int number;
    private double favorable = 0;
    int COUPON = 1;
    int ADDRESS = 2;
    String gmtTime;
    TextView coupins;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_affirm_order);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        llselectCoupons.setOnClickListener(view -> {
            if (couponInfos.size() != 0) {
                bundle.putDouble(Constants.ALLMONEY, allMoneyoney);
                bundle.putSerializable(Constants.COUPONS, (Serializable) couponInfos);
                bundle.putString(Constants.GMT, gmtTime);
                intent.putExtras(bundle);
                intent.setClass(context, SelectCouponsActivity.class);
                startActivityForResult(intent, COUPON);
            } else {
                showAlerDialog(1, "您在此餐馆没有优惠券");
            }

        });

        btOrderOk.setOnClickListener(view -> {
            if (addressInfoList.size() == 0 && type == 1) {
                showAlerDialog(1, "请先添加收货地址");
            } else {
                if (isVip.equals("4")) {
                    affirmOrder();
                    btOrderOk.setEnabled(false);
                } else {
                    toast("请加入会员后下单");
                }

            }
        });
        llSelectAddress.setOnClickListener(view -> {
            if (addressInfoList.size() != 0) {
                bundle.putString(Constants.TAG, AffirmOrderActivity.class.getName());
                intent.putExtras(bundle);
                intent.setClass(context, AddressActivity.class);
                startActivityForResult(intent, 1);
            } else {
                bundle.putInt(Constants.TYPE, 2);
                bundle.putString(Constants.TAG, AffirmOrderActivity.class.getName());
                intent.putExtras(bundle);
                intent.setClass(context, NewAddressActivity.class);
                startActivityForResult(intent, 1);
            }
        });
        toolbar.setNavigationOnClickListener(view -> AppManager.getAppManager().finishActivity(AffirmOrderActivity.class));
    }

    private void affirmOrder() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("userPhone", getString(Constants.USERPHONE));
//        map.put("card", vipInfos.get(0).getMem_card());
        map.put("card", TextUtils.isEmpty(vipInfos.get(0).getMem_card()) ? "[]" : vipInfos.get(0).getMem_card());
        map.put("uid", String.valueOf(getInt(Constants.USER_ID)));
        map.put("vipprice", turn(getIsVip(true), 1).toString());
        map.put("realprice", turn(getIsVip(false) + goToMoney - favorable, 1).toString());
        map.put("payType", String.valueOf(chooseTapye));
        map.put("lastprice", turn(lastprice, 1).toString());
        map.put("isosale", String.valueOf(type));
        map.put("ticket", turn(favorable, 1).toString());
        map.put("sumDishNumber", String.valueOf(number));
        map.put("username", getString(Constants.USERNAME));
        map.put("cards", getCardids());
        map.put("sendInfo", sendInfo());
        map.put("restrauntInfo", restrauntInfo());
        map.put("dishes", getAllDishes().toString());
        map.put("cg_discount", String.valueOf(restaurantInfo.getCg_discount()));
        Log.e("map===", map.toString());
        affirmOrderP.addData(Model.HTTPURL + Model.CLIENTORDER, map);
    }

    @Override
    public void sendAffirmError(VolleyError error) {

    }

    @Override
    public void sendRes(int res) {
        if (res == 0) {
            showAlerDialog(1, "下单失败,请再试一次。");
            btOrderOk.setEnabled(true);
        } else if (res == 1) {
            SweetAlertDialog sweetAlertDialog = new SweetAlertDialog(context, SweetAlertDialog.SUCCESS_TYPE);
            sweetAlertDialog.setTitleText("下单成功");
            sweetAlertDialog.setCancelable(false);
            sweetAlertDialog.setCanceledOnTouchOutside(false);
            sweetAlertDialog.setConfirmClickListener(sweetAlertDialog1 -> {
                AppManager.getAppManager().delAllActivityExceptMain(AffirmOrderActivity.class);
                sweetAlertDialog1.dismiss();
                bundle.putInt(Constants.JUMPPAGE, 2);
                bundle.putInt(Constants.JUMPPAGESON, type);
                startActivity(MainActivity.class, bundle);
            });
            sweetAlertDialog.show();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 结束Activity&从堆栈中移除
        AppManager.getAppManager().finishActivity(this);
    }

    private String restrauntInfo() {
        return "{" + "\"id\":\"" + restaurantInfo.getId() +
                "\",\"cg_name\":\"" + restaurantInfo.getCg_name() + "\",\"cg_phone\":\"" + restaurantInfo.getCg_phone() + "\"}";
    }

    private String sendInfo() {
        String sendInfo = "{" + "\"user_name\":\"" + affirName.getText().toString() + "\",\"user_phone\":\"" +
                affirPhone.getText().toString() + "\",\"addr\":\"" + affirAddress.getText() + "\"}";
        return sendInfo;
    }

    private StringBuffer getAllDishes() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("[");
        for (int i = 0; i < dishes.size(); i++) {
            buffer.append("{");
            buffer.append("\"dishes_no\":\"");
            buffer.append(dishes.get(i).getDishes_no());
            buffer.append("\",\"buyNum\":\"");
            buffer.append(dishes.get(i).getOrder_no());
            buffer.append("\",\"dishes_price\":\"");
            buffer.append(dishes.get(i).getDishes_price());
            buffer.append("\",\"dishes_vipprice\":\"");
            buffer.append(dishes.get(i).getDishes_vipprice());
            buffer.append("\",\"dishes_name\":\"");
            buffer.append(dishes.get(i).getDishes_name());
            buffer.append("\",\"dishes_pic\":\"");
            buffer.append(dishes.get(i).getDishes_pic());
            buffer.append("\"}");
            if (i != dishes.size() - 1) {
                buffer.append(",");
            }
        }
        buffer.append("]");
        return buffer;
    }

    private double  getIsVip(boolean isVip) {
        double allMoney = 0;
        for (int i = 0; i < dishes.size(); i++) {
            if (isVip) {
                allMoney = dishes.get(i).getOrder_no() * dishes.get(i).getDishes_vipprice() + allMoney;
            } else {
                allMoney = dishes.get(i).getOrder_no() * dishes.get(i).getDishes_price() + allMoney;
            }
        }
        return allMoney;
    }

    private String getCardids() {
        StringBuffer buffer = new StringBuffer();
        List<CouponInfo> chooseId = new ArrayList<>();
        for (CouponInfo couponInfo : couponInfos) {
            if (couponInfo.isChecked()) {
                chooseId.add(couponInfo);
            }
        }
        if (chooseId.size() != 0) {
            buffer.append("[");
            for (int i = 0; i < chooseId.size(); i++) {
                buffer.append("{");
                buffer.append("\"id\":\"");
                buffer.append(chooseId.get(i).getId());
                buffer.append("\"}");
                if (i != chooseId.size() - 1) {
                    buffer.append(",");
                }
            }
            buffer.append("]");
        } else {
            buffer.append("[]");
        }
        return buffer.toString();
    }

    private void initView() {





        affirmOrderP = new AffirmOrderP(this);
        setToolBar(toolbar, "确认订单", true);
        intent = getIntent();
        bundle = intent.getExtras();
        number = bundle.getInt(Constants.DISHESNO);
        dishes = (List<Dishes>) bundle.getSerializable(Constants.ORDERLIST);
        restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constants.RESTAURANT);
        cglowlimit = restaurantInfo.getCg_lowlimit();
        goToMoney = restaurantInfo.getCg_shipping();
        vipInfos = (List<VipInfo>) bundle.getSerializable(Constants.VIPINFO);
        men_geage = vipInfos.get(0).getMem_grade();
        type = bundle.getInt(Constants.TYPE);
        headerView = View.inflate(context, R.layout.affirm_heard, null);

        coupins = (TextView) headerView.findViewById(R.id.tv_selectcoupins);
        lladdress = (LinearLayout) headerView.findViewById(R.id.ll_address);
        llSelectAddress = (LinearLayout) headerView.findViewById(R.id.ll_select_address);
        addAddress = (TextView) headerView.findViewById(R.id.tv_add_address);
        affirName = (TextView) headerView.findViewById(R.id.tv_affirm_name);
        affirPhone = (TextView) headerView.findViewById(R.id.tv_affirm_phone);
        affirAddress = (TextView) headerView.findViewById(R.id.tv_affirm_address);
        payF = (TextView) headerView.findViewById(R.id.pay_f);
        llselectCoupons = (LinearLayout) headerView.findViewById(R.id.ll_select_coupons);
        //0表示店内 1表示外面
        if (type == 0) {
            cglowlimit = 0;
            goToMoney = 0;
            llSelectAddress.setVisibility(View.GONE);
        }
        if (men_geage == 2) {
            chooseTapye = 1;
            payF.setText("充值卡");
        } else {
            chooseTapye = 0;
        }
        initAdapter();
    }

    private void initAdapter() {
        setRecy(myRecyclerView);
        affirmAdapter = new AffirmAdapter(dishes,restaurantInfo);
        myRecyclerView.setAdapter(affirmAdapter);
        affirmAdapter.addHeaderView(headerView);
        addData();
    }

    private void addData() {
        affirmOrderP.addData(Model.HTTPURL + Model.CONFIRMORDER + "cgid=" + restaurantInfo.getId() + "&userPhone=" +
                getString(Constants.USERPHONE) + "&status=true");
    }

    @Override
    public void showdialog() {
        showDialog();
    }

    @Override
    public void dissmissdialog() {
            dissMissDialog();
    }

    @Override
    public void sendList(String isVip, double account, List<AddressInfo> addressInfoList, List<CouponInfo> couponInfos, String gmtTime) {
        this.isVip = isVip;
        this.addressInfoList = addressInfoList;
        this.account = account;
        this.couponInfos = couponInfos;
        this.gmtTime = gmtTime;
        if (addressInfoList.size() != 0) {
            addAddress.setVisibility(View.GONE);
            lladdress.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(affirName.getText().toString().trim()))
                affirName.setText(addressInfoList.get(0).getUser_name());
            if (TextUtils.isEmpty(affirPhone.getText().toString().trim()))
                affirPhone.setText(addressInfoList.get(0).getUser_phone());
            if (TextUtils.isEmpty(affirAddress.getText().toString().trim()))
                affirAddress.setText(addressInfoList.get(0).getAddr());
        } else {
            lladdress.setVisibility(View.GONE);
            addAddress.setVisibility(View.VISIBLE);
        }
        if (couponInfos.size() == 0) {
            llselectCoupons.setVisibility(View.GONE);
        }
        getLsatPrice();
    }

    private void getLsatPrice() {

        Log.e("dis===",getMyAllMoney()+"////-155"+restaurantInfo.getCg_discount());
        Log.e("dis2===",(199-155)*restaurantInfo.getCg_discount()/10+"");

        if (getMyAllMoney() >= cglowlimit) {
            goToMoney = 0;
        }
        if (men_geage == 0) {
            allMoneyoney = getMyAllMoney() - favorable + goToMoney;
            lastprice = allMoneyoney;
        } else if (men_geage == 1) {
            allMoneyoney = (getMyAllMoney() + goToMoney - favorable) * restaurantInfo.getCg_discount() / 10;
            lastprice = allMoneyoney;
        } else if (men_geage == 2) {
            if (getMyAllMoney() + goToMoney <= account) {
                allMoneyoney = getMyAllMoney() - favorable + goToMoney;
                lastprice = 0;
            } else {
                toast("您的余额不足，请及时充值");
                /*充值卡余额不足：（原价+运费-余额）*折扣率*/
                allMoneyoney = (getMyAllMoney() + goToMoney - favorable - account) * restaurantInfo.getCg_discount() / 10;
                lastprice = allMoneyoney;
            }
        }
        if (type == 1) {
            tvAffirmAllmoney.setText("共计￥" + turn(allMoneyoney, 1) + "元" + "（含" + turn(goToMoney, 1) + "元运费)");
        } else {
            tvAffirmAllmoney.setText("共计￥" + turn(allMoneyoney, 1) + "元");
        }
    }

    private double getMyAllMoney() {
        double allMoney = 0;
        for (int i = 0; i < dishes.size(); i++) {
            allMoney = dishes.get(i).getOrder_no() * dishes.get(i).getDishes_price() + allMoney;

        }
        return allMoney;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("resultCode======", resultCode + "");
        if (resultCode == COUPON) {
            couponInfos = (List<CouponInfo>) data.getSerializableExtra("newcoupons");
            favorable = data.getDoubleExtra("money", 0);
            coupins.setText("已优惠" + turn(favorable, 1) + "元");
            getLsatPrice();
        } else if (resultCode == ADDRESS) {
            Bundle bundle = data.getExtras();
            AddressInfo addressInfo = (AddressInfo) bundle.getSerializable(Constants.ADDRESSES);
            affirName.setText(addressInfo.getUser_name());
            affirPhone.setText(addressInfo.getUser_phone());
            affirAddress.setText(addressInfo.getAddr());
        } else {
            addData();
        }
    }


}
